<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;
use think\facade\Log;
use think\Validate;
use app\common\model\Config as ConfigModel;
use app\common\model\StudentTypeRel as StudentTypeRelModel;
use app\common\model\User as UserModel;
use app\common\model\BookExtraDraw as BookExtraDrawModel;
use app\common\model\BookApply as BookApplyModel;
use app\common\model\PlanStudentRel as PlanStudentRelModel;
use think\model\concern\SoftDelete;

class StudentInfo extends Common
{
    protected $pk = 'xh';
    
    /**
     * 设置csv header
     * @return array
     */
    public function csvHeader()
    {
        return [
            [
                'id'   => 'xh',
                'desc' => '学生学号',
            ],
            [
                'id'   => 'xm',
                'desc' => '学生姓名',
            ],
            [
                'id'   => 'dir',
                'desc' => '方向',
            ],
            [
                'id'   => 'mobile',
                'desc' => '辅导员手机',
            ],
            [
                'id'   => 'truename',
                'desc' => '辅导员姓名',
            ]
        ];
    }

    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        $list = $this->field($tableWhere['field'])->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;

        return $re;
    }

    /**
     *  修改学生信息
     * User:tony
     * @param $data
     * @return array
     */
    public function saveData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data' => []
        ];

        if($data['teacherId'] == '') { 
            $result['status'] = false;
            $result['msg'] = '请选择辅导员';
            return $result;
        }

        if($data['dir'] == '') { 
            $result['status'] = false;
            $result['msg'] = '请选择方向';
            return $result;
        }

        $configModel = new ConfigModel();
        $year = $configModel->getYear();
        $season = $configModel->getSeason();
        if(isset($data['types'])){
            // 判断本次是否修改了类型
            $bookExtraDrawModel = new BookExtraDrawModel(); 
            $typeList = $bookExtraDrawModel->field('a.type_id, a.param_id')
                    ->alias('a')
                    ->join('zl_book_extra_draw_detail b', 'a.id = b.draw_id')
                    ->where(['a.year' => $year, 'a.season' => $season, 'b.xh' => $data['xh']])
                    ->select();
            
            foreach($typeList as $item) {
                if(isset($data['types'][$item['type_id']]) && $data['types'][$item['type_id']] != $item['param_id']){ 
                    // 修改了已经发放的类型参数
                    $result['status'] = false;
                    $result['msg'] = '该类型对应的教材已经发放，不允许修改';
                    return $result;
                }
            }
        }

        // 如果更改了辅导员且存在申请为领书的情况，则需要删除该学生的申请记录
        $bookApplyModel = new BookApplyModel();
        $qsInfo = $bookApplyModel->getIsqs($year, $season, $data['xh']);

        if($qsInfo && $qsInfo['is_qs'] == '0') {
            // 获取申请时的所在的班级
            $planStudentRelModel = new PlanStudentRelModel();
            $relInfo = $planStudentRelModel->where(['plan_code'=>$qsInfo['class_id']])->find();
            // 获取申请时学生所在班级的所有辅导员
            $teacherIdListWhere = [];
            $teacherIdListWhere[] = ['bjdm', 'eq', $relInfo['bjdm']];
            $teacherIdListWhere[] = ['teacherId', 'neq', ''];

            $teacherIdList = $this->field('teacherId')
                                ->distinct(true)
                                ->where($teacherIdListWhere)
                                ->select();

            $bFind = false;
            foreach($teacherIdList as $val) {
                if($data['teacherId'] == $val['teacherId']) {
                    $bFind = true;
                }
            }
            
            // 已经提交了审核尚未签收，且目标老师不是本班老师则不允许修改辅导员
            if($bFind == false) {
                $result['status'] = false;
                $result['msg'] = '存在申请未领取记录，请先删除申请后再修改辅导员！';
                return $result;
            }
        }
        
        $saveData = [];
        $saveData['teacherId'] = $data['teacherId'];
        $saveData['dir'] = $data['dir'];
 
        if (!$this->allowField(true)->save($saveData,['xh'=>$data['xh']]))
        {
            $result['status'] = false;
            $result['msg'] = '保存失败';
            return $result;
        }
 
        // 保存类型
        //清空所有的旧类型
        $studentTypeRelModel = new StudentTypeRelModel();
        $studentTypeRelModel->where(['plan_year' => $year, 'plan_season' => $season, 'xh' => $data['xh']])->delete();
  
        if(isset($data['types'])){
            $typeData = [];
            foreach($data['types'] as $k => $v){
                if($v != '') {
                    $row['xh'] = $data['xh'];
                    $row['plan_year'] = $year;
                    $row['plan_season'] = $season;
                    $row['type_id'] = $k;
                    $row['param_id'] = $v;
                    $typeData[] = $row;
                }
            }
            $studentTypeRelModel->saveAll($typeData);
        }
        \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $result;
    }

    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['xh']) && $post['xh'] != ""){
            $where[] = ['xh', 'like', '%'.$post['xh'].'%'];
        }
        
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['xh ASC'];
        return $result;
    }


    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        foreach($list as &$val){
           // $val['logo'] = _sImage($val['logo']);
           // $val['utime'] = getTime($val['utime']);
        }
        return $list;
    } 
    
    /**
     * 返回usernamelist
     * @author tony
     * @param $post
     * @return mixed
     */
    public function getXhList()
    {
        $list       = [];
        $list = $this->field('xh')->select();

        $usernameArray = $list->toArray();
        $usernameList = [];
        foreach ($usernameArray as $k => $v) {
            $usernameList[] = $v['xh'];
        }
         
        return $usernameList;
    }

    /**
     * 返回mobilelist
     * @author tony
     * @param $post
     * @return mixed
     */
    public function getXhNameList()
    {
        $list       = [];
        $list = $this->field('concat(xh,xm) as xh')->select();

        $mobileArray = $list->toArray();
        $mobileList = [];
        foreach ($mobileArray as $k => $v) {
            $mobileList[] = $v['xh'];
        }
         
        return $mobileList;
    }
    
    /**
     * 返回mobilelist
     * @author tony
     * @param $post
     * @return mixed
     */
    public function getXhTeacherUnDrawList()
    {
        $list       = [];

        $configModel = new ConfigModel();
        $year = $configModel->getYear();
        $season = $configModel->getSeason();

        $list = $this->field('a.xh')
            ->alias('a')
            ->join('zl_book_apply_detail b', 'b.xh = a.xh and b.is_qs = 0')
            ->join('zl_book_apply c', 'c.id = b.applyid')
            ->where(['c.year' => $year, 'c.season' => $season])
            ->select();

        $unDrawArray = $list->toArray();
        $unDrawList = [];
        foreach ($unDrawArray as $k => $v) {
            $unDrawList[] = $v['xh'];
        }
         
        return $unDrawList;
    }

    /**
     * 同步财务数据
     * @author tony
     * @param $post
     * @return mixed
     */
    public function sync()
    {
        $result = [
            'status' => true,
            'msg' => '同步成功'
        ];

		// 清理财务班级与现有班级不一致学生未发放的申请
        $bookApplyModel = new BookApplyModel();
        $where[] = ['student.bjdm != xsdm.bjdm'];
        $idList = $bookApplyModel->alias('apply')
            ->field('detail.id')
            ->join('zl_book_apply_detail detail', 'apply.id = detail.applyid')
            ->join('zl_student_info student', 'detail.xh = student.xh')
            ->join('zlzhsf.pxsdm xsdm', 'student.xh = xsdm.xh and student.bjdm <> xsdm.bjdm')
            ->select();

        // 有申请记录的，需要处理申请状态
        foreach ($idList as $val) { 
            $this->query('call bookDrawDelStudent('.$val['id'].');');
        }

        $this->query('call syncStudentInfo;');
        $this->query('call syncClassList;');
        
        return $result;
    }

    public function getAssistantInfo($post)
    {
        $mobile = $post['mobile'];
        // 获取当前用户所属部门
        $deptList = $this->field('plan_dep_id')
            ->distinct(true)
            ->alias('a')
            ->join('zl_plan_student_rel b', 'a.bjdm = b.bjdm and a.dir = b.dir')
            ->join('zl_book_plan c', 'b.plan_code = c.plan_code')
            ->join('zl_user d', 'a.teacherId = d.id')
            ->where(['mobile' => $mobile])
            ->select();
 
        // 获取用户所负责的部门
        $ids = ''; 
        // 有申请记录的，需要处理申请状态
        foreach ($deptList as $val) { 
            $ids = $ids . ',' . $val['plan_dep_id']; 
        }

        $userModel = new UserModel();
        $userInfo = $userModel->where(['mobile' => $mobile])->find();
        if($userInfo) {
            $ids = $ids . ',' . $userInfo['deptId']; 
        }

        if (substr($ids, 0, 1) == ',') {
            $ids = substr($ids, 1);
        }
 
        $where = [];
        $where[] = ['deptId', 'in', $ids];

        return $userModel->alias('user')
                ->field("user.mobile, user.truename")
                ->leftjoin('zl_assistant_user_rel rel1', 'user.mobile = rel1.assistantUserMobile')
                ->leftjoin('zl_assistant_user_rel rel2', 'user.mobile = rel2.userMobile')
                ->where($where)
                ->where('mobile', 'neq', $mobile)
                ->whereNull('rel1.assistantUserMobile')
                ->whereNull('rel2.userMobile')
                ->select();
    }
     
}